﻿using System;
using System.Runtime.InteropServices;

namespace InnovTech.Net
{
    public static class ConnectionUtil
    {

        /// <summary>
        /// Checks whether the internet connection is avaliable.
        /// </summary>
        /// <returns>True, when the internet connection ist avaliable.</returns>
        public static bool GetIsInternetAvaliable()
        {
            int Desc;
            bool state = InternetGetConnectedState(out Desc, 0);
            return state;
        }
        
        /// <summary>
        /// Checks whether a server is avaliable for now.
        /// </summary>
        /// <param name="serverUri">The server Uri.</param>
        /// <returns>True, when the remote server is avaliable.</returns>
        public static bool CheckIsServerAvaliable(string serverUri)
        {
            return InternetCheckConnection(serverUri, FLAG_ICC_FORCE_CONNECTION, 0);
        }


        #region Interop items

        [Flags]
        enum InternetConnectionState_e : int
        {
            //uses modem
            INTERNET_CONNECTION_MODEM = 0x1,
            //uses lan
            INTERNET_CONNECTION_LAN = 0x2,
            //uses proxy
            INTERNET_CONNECTION_PROXY = 0x4,
            //intalled RAS (Remote Access Service, for example VPN)
            INTERNET_RAS_INSTALLED = 0x10,
            //offline mode
            INTERNET_CONNECTION_OFFLINE = 0x20,
            //There is connection, but not be used
            INTERNET_CONNECTION_CONFIGURED = 0x40
        }

        //This method return a true, when there is a connection by a modem or LAN
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

        

        //InternetCheckConnection uses only this flag for now.
        private const int FLAG_ICC_FORCE_CONNECTION = 0x1;
        [DllImport("wininet.dll")]
        private extern static bool InternetCheckConnection(string uri, int flag, int reservedValue);


        #endregion interop items

    }
}
